<?php
/**
 * Created by PhpStorm.
 * User: 84071
 * Date: 2017-09-07
 * Time: 11:47
 */
namespace app\common\model;
use think\Db;
use think\db\Query;
use think\Model;
class UserAddress extends Model{
    // 开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    protected $insert = ['addtime','addip'];
    protected $type = [
        'addtime'    => 'timestamp',
    ];
    // 定义时间戳字段名
    protected $createTime = 'addtime';
    protected $updateTime = false;
    protected function setAddipAttr(){
        return request()->ip();
    }

    //  获取并处理单一地址
    public function one_addres($data){
        $id = empty($data['id']) ? null:$data['id'];
        $uid = empty($data['uid']) ? null:$data['uid'];
        $adduname = empty($data['adduname']) ? null:$data['adduname'];
        $phone = empty($data['phone']) ? null:$data['phone'];
        $addres = empty($data['addres']) ? null:$data['addres'];
        //  分页
        $pnum = empty($data['pnum'])?'20':$data['pnum'];
        $page = empty($data['page']) ? '1' : $data['page'];
        //  构造查询语句
        $query = new Query();
        $query = $query->name('user_address');
        if(!empty($id)){
            $query = $query->where('id',$id);
            $map['id'] = $id;
        }
        if(!empty($uid)){
            $query = $query->where('uid',$uid);
            $map['uid'] = $uid;
        }
        if(!empty($adduname)){
            $query = $query->where('adduname',$adduname);
            $map['adduname'] = $adduname;
        }
        if(!empty($phone)){
            $query = $query->where('phone',$phone);
            $map['phone'] = $phone;
        }
        if(!empty($addres)){
            $query = $query->where('addres','in',$addres);
            $map['addres'] = array('in',$addres);
        }
        $query = $query->order("addtime desc")->limit($pnum)->page($page);
        //  查询
        if($data['f'] == 'find'){
            $cont = $query->find();
            $cont['addresarr'] = explode(',',$cont['addres']);
            return $cont;
        }
        if($data['f'] == 'select'){
            //  执行sql语句
            $_listdata = Db::select($query);
            //  获取所有数量
            $listmun = $this->where($map)->count();
            $pages = ceil($listmun/$pnum);
            //  格式化查询到的数据
            $listdata = null;
            if(!empty($_listdata)){
                foreach ($_listdata as $k => $v){
                    $listdata[$k] = $this->unserializeData($v);
                }
            }
            if(empty($listdata)){
                return false;
            }else{
                $res = array(
                    'list' => $listdata,
                    'pages' => $pages,
                    'page' => $page,
                    'pagenum' => $listmun,
                );
            }
            return $res;
        }


    }


}